//
//  HeroOneHyOpenGLView.m
//  opengl-es2.0绘制流程
//
//  Created by yanhe on 2017/9/14.
//  Copyright © 2017年 yanhe. All rights reserved.
//

#import "HeroOneHyOpenGLView.h"
#import <GLKit/GLKit.h>

#define PI 3.14159265

@interface HeroOneHyOpenGLView()
@property (nonatomic, strong) EAGLContext *context;
@property (nonatomic, readonly) GLint drawableWidth;
@property (nonatomic, readonly) GLint drawableHeight;
@property (strong, nonatomic) GLKBaseEffect *baseEffect;
@property (nonatomic , assign) GLuint   myProgram;
@end
@implementation HeroOneHyOpenGLView

+ (Class)layerClass
{
    return [CAEAGLLayer class];
}
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
        eaglLayer.drawableProperties =
        [NSDictionary dictionaryWithObjectsAndKeys:
         [NSNumber numberWithBool:NO],
         kEAGLDrawablePropertyRetainedBacking,
         kEAGLColorFormatRGBA8,
         kEAGLDrawablePropertyColorFormat,
         nil];
        
        //初始化上下文
        EAGLContext *context =  [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES2];
        self.context = context;
        [EAGLContext setCurrentContext:context];
        
        //设置并绑定帧缓存和渲染缓存
        glGenFramebuffers(1, &defaultFrameBuffer);
        glBindFramebuffer(GL_FRAMEBUFFER,defaultFrameBuffer);
        glGenRenderbuffers(1, &colorRenderBuffer);
        glBindRenderbuffer(GL_RENDERBUFFER,colorRenderBuffer);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_RENDERBUFFER,colorRenderBuffer);
        //绑定渲染缓存和图层
        [self.context renderbufferStorage:GL_RENDERBUFFER
                             fromDrawable: (CAEAGLLayer *)self.layer];
        
        
        //读取文件路径
        NSString* vertFile = [[NSBundle mainBundle] pathForResource:@"shaderv" ofType:@"vsh"];
        NSString* fragFile = [[NSBundle mainBundle] pathForResource:@"shaderf" ofType:@"fsh"];
        //加载shader
        self.myProgram = [self loadShaders:vertFile frag:fragFile];
        //链接
        glLinkProgram(self.myProgram);
        
        [self display];
    }
    return self;
}
-(void)display
{
   
 
    //设置视口坐标 视口坐标的原点是view的左下角
     glViewport(0, 0, self.drawableWidth, self.drawableHeight);
    glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
     glClear(GL_COLOR_BUFFER_BIT);

     //使用shader
    glUseProgram(self.myProgram);
  
    float p0[]  = {3, 8};
    float p1[]  = {4, 3};
    float p2[]  = {2, 7};
    float result[10][2]  = {};
    for (int i = 0; i < 10; i++) {
        float t = i / 10;
        result[i][0] = (float) (1 * pow(1 - t, 2) * pow(t, 0) * p0[0] + 2 * pow(1 - t, 1) * pow(t, 1) * p1[0] + 1 * pow(1 - t, 0) * pow(t, 2) * p2[0]);
        result[i][1] = (float) (1 * pow(1 - t, 2) * pow(t, 0) * p0[1] + 2 * pow(1 - t, 1) * pow(t, 1) * p1[1] + 1 * pow(1 - t, 0) * pow(t, 2) * p2[1]);
    }
   
    
    //画四叶草
  const int n=76;
    
    float r = 0.0;
    float x0 = -0.3;
    float y0 = -0.3;
    double x, val, res;
    x = 1.0;
    val = PI / 180;
    GLfloat vertexes[n][3] ={}; //n必须是常数
    for (int i=0; i<n; i++) {
        for (int j=0; j<3; j++) {
            res = (x+i)*5*val;
            r = 0.5*(cos(res*3)); //res*2是四叶草，*3是3叶草，r=a*res是螺旋线
            if (j==0) {
                vertexes[i][j] = x0+r*cos(res);
            }else if (j==1){
                vertexes[i][j] = y0+r*sin(res);
            }else if (j==2){
                vertexes[i][j] = 0.0f;
            }
        }
    }
    glVertexAttribPointer(0, 3, GL_FLOAT, 0, 0, &vertexes[0][0]);
    glEnableVertexAttribArray(0);
    
    
    glDrawArrays(GL_POINTS,      // STEP 6
                 0,  // Start with first vertex in currently bound buffer
                 n);
    
     [self.context presentRenderbuffer:GL_RENDERBUFFER];
    
}
//创建program
- (GLuint)loadShaders:(NSString *)vert frag:(NSString *)frag {
    GLuint verShader, fragShader;
    GLint program = glCreateProgram();
    
    //编译
    [self compileShader:&verShader type:GL_VERTEX_SHADER file:vert];
    [self compileShader:&fragShader type:GL_FRAGMENT_SHADER file:frag];
    
    glAttachShader(program, verShader);
    glAttachShader(program, fragShader);
    
    
    //释放不需要的shader
    glDeleteShader(verShader);
    glDeleteShader(fragShader);
    
    return program;
}
//创建顶点shader和片元shader
- (void)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file {
    //读取字符串
    NSString* content = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
    const GLchar* source = (GLchar *)[content UTF8String];
    
    *shader = glCreateShader(type);
    glShaderSource(*shader, 1, &source, NULL);
    glCompileShader(*shader);
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    //删除缓存
    if (0 != defaultFrameBuffer)
    {
        glDeleteFramebuffers(1, &defaultFrameBuffer); // Step 7
        defaultFrameBuffer = 0;
    }

    if (0 != colorRenderBuffer)
    {
        glDeleteRenderbuffers(1, &colorRenderBuffer); // Step 7
        colorRenderBuffer = 0;
    }
    if (0 != vertexBufferID)
    {
        glDeleteBuffers (1,          // STEP 7
                         &vertexBufferID);
        vertexBufferID = 0;
    }

    self.context = nil;
    [EAGLContext setCurrentContext:nil];
  
}
- (GLint)drawableWidth;
{
    GLint          backingWidth;
    //获取屏幕分辨率的宽度
    glGetRenderbufferParameteriv(
                                 GL_RENDERBUFFER,
                                 GL_RENDERBUFFER_WIDTH,
                                 &backingWidth);
    
    return backingWidth;
}

- (GLint)drawableHeight;
{
    GLint          backingHeight;
    //获取屏幕分辨率的高度
    glGetRenderbufferParameteriv(
                                 GL_RENDERBUFFER,
                                 GL_RENDERBUFFER_HEIGHT,
                                 &backingHeight);
    
    return backingHeight;
}

@end
